package com.xuanwei.search.controller;

import com.xuanwei.search.entity.index.ProductIndex;
import com.xuanwei.search.service.ProductSearchService;
import com.xuanwei.xwcommon.entity.Vo.ProductVo;
import com.xuanwei.xwcommon.entity.dto.R;
import com.xuanwei.xwcommon.entity.dto.SimpleProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("es")
@Slf4j
public class ProductController {

    private ProductSearchService productSearchService;

    public ProductController(ProductSearchService productSearchService) {
        this.productSearchService = productSearchService;
    }

    @RequestMapping(value = "add", method = RequestMethod.POST)
    public R add(@RequestBody ProductIndex productIndex) throws Exception {
        if (productIndex == null) {
            log.error("productIndex is null");
            return new R().fail();
        }
        productSearchService.add(productIndex);
        return new R().ok();
    }

    @RequestMapping(value = "search", method = RequestMethod.GET)
    public R search(String name, Integer categoryId,
                    Integer orderBy, Integer page,
                    Integer pageSize, Integer order) {
        List<SimpleProductDto> search = productSearchService.search(name, categoryId, orderBy, page, pageSize, order);
        return new R().ok().data(search);
    }

    @RequestMapping(value = "detail", method = RequestMethod.GET)
    public R detail(Integer id) {
        ProductIndex byId = productSearchService.findById(id);
        ProductVo productVo = new ProductVo();
        BeanUtils.copyProperties(byId, productVo);
        productVo.setBannerImages(Arrays.asList(byId.getBannerImage().split(",")));
        return new R().ok().data(productVo);
    }

    @RequestMapping(value = "delete", method = RequestMethod.GET)
    public R delete(Integer id) {
        productSearchService.deleteById(id);
        return new R().ok();
    }

    @RequestMapping(value = "simpleDetail", method = RequestMethod.GET)
    public R simpleDetail(Integer id) {
        SimpleProductDto simpleProductDto = productSearchService.findSimpleProductById(id);
        return new R().ok().data(simpleProductDto);
    }

}
